
#include "linklist.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include <pthread.h>

#define THREAD_NUM  10



typedef struct timer_tick{
	unsigned int period;	//
	unsigned int cur;
	int (*call_back)(int num);
	pthread_mutex_t mutex;
}TimerTick;

int func_1(int a)
{
	printf("timout [%s] %d \n", __func__, a);
}


int func_2(int a)
{
	printf("timout [%s] %d \n", __func__, a);
}


//若该函数执行时间过长，可以将其修改为线程池，避免影响主线程的时间
int tick(void * data)
{
	TimerTick *t = (TimerTick *)data;
	if(!t)
		return -1;
	pthread_mutex_lock(&t->mutex);
	t->cur ++;
	if(t->cur >= t->period){
		if(t->call_back){
			t->call_back(t->cur);
		}
		t->cur = 0;
	}
	pthread_mutex_unlock(&t->mutex);
	return 0;
}


linklist_s *list;

int main()
{
	
    int i = 5;
    pthread_t pid[32];
	char *p = NULL;
	TimerTick *t;
	TimerTick timer[3] = {
		{2, 0, func_1, PTHREAD_MUTEX_INITIALIZER},
		{5, 0, func_2, PTHREAD_MUTEX_INITIALIZER},
		{10, 0, func_2, PTHREAD_MUTEX_INITIALIZER}
	};
	
    list = list_init(NULL);
    if(!list){
        return 0;
    }
	
	//注册
	list_add_node(list, &timer[0], sizeof(TimerTick));
	list_add_node(list, &timer[1], sizeof(TimerTick));
	list_add_node(list, &timer[2], sizeof(TimerTick));
	
	while(1){
		//对每个注册的结构体执行相同的函数
		for_each(list, tick);
		sleep(1);
	}
	
	char buf[512] = {0};
	while(0 ==list_pop_node(list, buf)){
		printf("buf = %s\n",buf);
		memset(buf, 0, sizeof(buf));
	}
	
	list_clear(list);

	

}
